import cv2
import numpy as np

from _0work_tools import cv_show
from _03fulfill import fulfill_border
from _0work_tools import box_filter_factor

"""
@Project: pythonPro1
@Name: _04smooth.py
@Author: linxin_liu
@Date: 2022/10/15 11:09
"""


def average_blur(img, size, blur_type):  # 这里只做了3*3的相关。
    # 均值虑波器，传入图片，盒子大小(n*n)。
    # 生成size[0]*size[1]大小且元素值都为1的二维列表。此列表就是盒子。
    box_filter = box_filter_factor(size, 1)
    # 开始滤波
    full_imag = fulfill_border(img, 1, 1, 1, 1, 'black')  # 先将图片加大一圈，那一圈值为0.
    # 开始循环遍历
    for i in range(len(img)):  # 大的双循环只需要遍历 原始图像的高*宽 次。
        for j in range(len((img[0]))):
            if blur_type == 'average':  # 均值滤波器
                # 取大图片的9个值分别与模板的9个值相乘，再相加，再除以9(取整)。
                counts = \
                    full_imag[i][j]*box_filter[0][0] + full_imag[i][j+1]*box_filter[0][1] + full_imag[i][j+2]*box_filter[0][2] + \
                    full_imag[i+1][j]*box_filter[1][0] + full_imag[i+1][j+1]*box_filter[1][1] + full_imag[i+1][j+2]*box_filter[1][2] + \
                    full_imag[i+2][j]*box_filter[2][0] + full_imag[i+2][j+1]*box_filter[2][1] + full_imag[i+2][j+2]*box_filter[2][2]
                img[i][j] = counts // 9
            elif blur_type == 'gauss':  # 高斯滤波器
                box_filter[1][1] = 4
                # 取大图片的9个值分别与模板的9个值相乘，再相加，再除以10(取整?)。
                counts = \
                    full_imag[i][j]*box_filter[0][0] + full_imag[i][j+1]*box_filter[0][1] + full_imag[i][j+2]*box_filter[0][2] + \
                    full_imag[i+1][j]*box_filter[1][0] + full_imag[i+1][j+1]*box_filter[1][1] + full_imag[i+1][j+2]*box_filter[1][2] + \
                    full_imag[i+2][j]*box_filter[2][0] + full_imag[i+2][j+1]*box_filter[2][1] + full_imag[i+2][j+2]*box_filter[2][2]
                img[i][j] = counts // 12
            elif blur_type == 'median':  # 中值滤波器
                nums = [full_imag[i][j] * box_filter[0][0], full_imag[i][j + 1] * box_filter[0][1],
                        full_imag[i][j + 2] * box_filter[0][2], full_imag[i + 1][j] * box_filter[1][0],
                        full_imag[i + 1][j + 1] * box_filter[1][1], full_imag[i + 1][j + 2] * box_filter[1][2],
                        full_imag[i + 2][j] * box_filter[2][0], full_imag[i + 2][j + 1] * box_filter[2][1],
                        full_imag[i + 2][j + 2] * box_filter[2][2]]
                nums.sort()  # 排序
                img[i][j] = nums[4]
    return img


if __name__ == '__main__':
    img_original = cv2.imread('D:/tools/image_operation/lenaNoise.png')  # , cv2.IMREAD_GRAYSCALE
    img_G = img_original[:, :, 0]
    img_B = img_original[:, :, 1]
    img_R = img_original[:, :, 2]
    average_blur_G = average_blur(img_G, [3, 3], 'median')
    average_blur_B = average_blur(img_B, [3, 3], 'median')
    average_blur_R = average_blur(img_R, [3, 3], 'median')
    all_image = cv2.merge((img_B, img_G, img_R))  # 融合三个通道的像素形成一张彩图。
    cv_show('a', all_image, 1000)
    cv2.imwrite('D:/tools/image_operation/girl_median.png', all_image)
